import { HashMap } from '../utils/hashmap'
import $ from 'jquery'
import 'jquery-ui-dist/jquery-ui'
import 'jquery-ui-dist/jquery-ui.css'
import '../utils/jquery.contextmenu.r2'

export const TemplateOptions = {
    methods: {
        layoutInit() {
            this.widgetData = new HashMap();
            this.widgetData.clear();
            $('#compont').html('');
            $('#accordion').find('a').each(function () {
                $(this).removeClass('notclick');
                $(this).addClass('addWiget');
            });

            if (this.twidget === undefined || this.twidget == null || this.twidget.length < 1) {
                return;
            }
            var coindex = 0;
            let _this = this;
            $.each(this.twidget,function(i) {
                coindex++;
                var type = _this.twidget[i]['type'];
                var keyid = type + _this.twidget[i]['index']
                _this.widgetData.put(keyid, _this.twidget[i]);
                _this.addWiget(_this.twidget[i], type);
            });
            $('#accordion').find('a').attr('index',coindex);
            setTimeout(() => {
                $.each(this.twidget,function(i) {
                    var keyid = _this.twidget[i]['type'] + _this.twidget[i]['index'];
                    var screen = _this.twidget[i]['screen']
                    if(!screen) {
                        setTimeout(() => {
                            _this.doUpdateAttrForm(keyid)
                        }, 100)
                    }
                })
            }, 200);
        },
        // 修改模板类型
        async doChangeResolution(resolution) {
            let _this = this;
            let len = this.widgetData.size()
            let res = true
            if(len > 0) {
                res = await this.$confirm('提示', '更换分辨率会清空区域，确认要更换吗？')
            }
            if (res) {
                _this.parseResolution(resolution);
                _this.widgetData.clear();
                _this.resetVal();
                _this.twidget = []
                $('#compont').html('');
                $('#accordion').find('a').each(function () {
                    $(this).removeClass('notclick');
                    $(this).addClass('addWiget');
                });
                return true
            }
            return false
        },
        // 更新属性值
        doUpdateAttrForm(key) {
            $('#right').attr('currentSelectedWidgetId', key);
            const itemData = this.widgetData.get(key)
            const x = itemData['x']
            const y = itemData['y']
            const w = itemData['width']
            const h = itemData['height']
            const name = itemData['name']
            const svl = itemData['svl']
            this.$nextTick(() => {
                this.attrForm.X = x
                this.attrForm.Y = y
                this.attrForm.W = w
                this.attrForm.H = h
                this.attrForm.name = name
                this.attrForm.svl = svl ? svl : 0
                // console.log('被选择', itemData, this.attrForm)
            })
        },
        parseResolution(resolution) {
            this.templateOpts = {
                width: Number(resolution.split('*')[0]),
                height: Number(resolution.split('*')[1].match(/[0-9]*/)[0])
            }
        },
        widgetUpdate(view, itemData) {
            const x = Number(itemData['x'])
            const y = Number(itemData['y'])
            const w = Number(itemData['width'])
            const h = Number(itemData['height'])

            view.css('top', `${y * this.iheightPercent}px`)
            view.css('left', `${x * this.iwidthPercent}px`)
            view.css('width', `${w * this.iwidthPercent}px`)
            view.css('height', `${h * this.iheightPercent}px`)
        },
        widgetResize(view,left,top,width,height,drag) {
            var keyId = view.attr('id');
            if ((left + width) > this.wrapperWidth) {
                width = this.wrapperWidth - left;
            }
            if ((top + height) > this.wrapperHeight) {
                height = this.wrapperHeight - top;
            }
            if (drag) {
                let x = Math.round(left / this.iwidthPercent);
                let y = Math.round(top / this.iheightPercent);
                let w = this.widgetData.get(keyId)['width'];
                let h = this.widgetData.get(keyId)['height'];
                if(( x + w) > Number(this.templateOpts.width)) {
                    x = Number(this.templateOpts.width) - w
                }
                if(( y + h) > Number(this.templateOpts.height)) {
                    y = Number(this.templateOpts.height) - h
                }
                // 更新xy坐标值
                this.$nextTick(() => {
                    this.attrForm.X = x
                    this.attrForm.Y = y
                    if (this.widgetData.containsKey(keyId)) {
                        this.widgetData.get(keyId)['x'] = x;
                        this.widgetData.get(keyId)['y'] = y;
                    }
                })

            } else {
                let w = Math.round(width / this.iwidthPercent);
                let h = Math.round(height / this.iheightPercent);
                if(w > Number(this.templateOpts.width)) {
                    w = this.templateOpts.width
                }
                if(h > Number(this.templateOpts.height)) {
                    h = this.templateOpts.height
                }
                this.$nextTick(() => {
                     // 更新wh高宽度
                    this.attrForm.W = w
                    this.attrForm.H = h
                    if (this.widgetData.containsKey(keyId)) {
                        this.widgetData.get(keyId)['width'] = w;
                        this.widgetData.get(keyId)['height'] = h;
                    }
                })

            }
        },
        widgetSelected($this) {
            var key = $this.attr('id');
            var type = $this.attr('type');
            this.updateSelectedWidgetParams(key, type, $this.attr('name'))
        },
        // 获取widget相关信息
        __getWidgetInfo(widget) {
            return {
                x: this.__px2real(widget.css('left')),
                y: this.__px2real(widget.css('top')),
                width: this.__px2real(widget.css('width')),
                height: this.__px2real(widget.css('height')),
                name: widget.attr('name'),
                z: widget.css('z-index')
            }
        },
        // px 2 number
        __px2number(px) {
            return Number(px.replace('px', ''))
        },
        // px 2 real 元素px值转实际模版值
        __px2real(px) {
            return Math.round(this.__px2number(px) / this.iwidthPercent)
        },
        // 给widget设置素材
        __widgetSetElement(widget, elementOpts) {
            const eleStyle = 'width: 100%; height: 100%; position: absolute; top: 0px; left: 0px; right: 0px; bottom: 0px;'
            switch(elementOpts.type) {
                case 'video':
                    widget.html(`<video autoplay src="${elementOpts.url}" style="${eleStyle}" />`)
                    break;
                case 'img':
                    widget.html(`<img src="${elementOpts.url}" style="${eleStyle}" />`)
                    break;
                default:
            }
        },
        // 刷新属性参数
        updateSelectedWidgetParams(key, type, name) {
            $('#areaName').attr('widgetId', key);
            $('#areaName').val(name);
            if (this.widgetData.containsKey(key)) {
                this.doUpdateAttrForm(key)
            } else {
                this.resetVal()
            }
        },
        updateSelectedWidget(val, flag) {
            const currentSelectedWidgetId = $('#right').attr('currentSelectedWidgetId');
            let _this = this;
            $('#compont').children().each(function() {
                const id = $(this).attr('id');
                const itemData = _this.widgetData.get(id);
                    if (itemData != null && id === currentSelectedWidgetId) {
                        const isValid = _this.isModifyValid(val, flag, itemData);
                        if (!isValid) {
                            _this.$alert('提示', '已经超出分辨率')
                            return;
                        }
                        switch (flag) {
                            // 改X坐标
                            case 1:
                                $(this).css("left", `${val * _this.iwidthPercent}px`);
                                itemData['x'] = Number(val)
                                break
                            // 改Y坐标
                            case 2:
                                $(this).css('top', `${val * _this.iheightPercent}px`)
                                itemData['y'] = Number(val)
                                break
                            // 改svl
                            case 3:
                                itemData['svl'] = Number(val)
                                break
                        }
                    }
                // }
            });
        },
        isModifyValid(srx,flag,itemData) {
            var retVal = true;
            var iW = 0;
            var iH = 0;
            var iX = 0;
            var iY = 0;
            switch (flag) {
                case 1:
                    iW = Number(this.attrForm.X) + Number(srx);
                    if (iW > this.templateOpts.width) {
                        this.attrForm.X = itemData['x']
                        retVal = false;
                    }
                    break;
                case 2:
                    iH = Number(this.attrForm.Y) + Number(srx);
                    if (iH > this.templateOpts.height) {
                        this.attrForm.Y = itemData['y']
                        retVal = false;
                    }
                    break;
            }
            return retVal;
        },
        addWiget(itemData, type) {
            var divAdd = $('#screenC').clone()
            var keyId = type + itemData['index'];
            // if (type === 'Imp' || type === 'Text' || type === 'Button' || type === 'Hd') {
            var widget = $('#accordion').find('a[name=' + type + ']');
            widget.removeClass('addWiget');
            widget.addClass('notclick');
            var widExist = $('#compont').find('[id=' + keyId + ']');
            if (widExist.length > 0) {
                return;
            }
            // }
            var screen = itemData['screen']
            divAdd.css('display','block').css('position','absolute').attr('name', itemData['name']).attr('id',keyId).attr('type',type);
            if(screen && screen !== '1') {
                divAdd.find('img').attr('src', screen)
            }
            this.widgetUpdate(divAdd, itemData);
            // if(!screen) {
            //     let _this = this;
            //     divAdd.draggable({
            //         containment: '#compont',
            //         scroll: false,
            //         // stack: '#compont div',
            //         opacity: 0.5,
            //         drag: function(event, ui) {
            //             _this.widgetResize(divAdd,ui.position.left,ui.position.top,divAdd.width(),divAdd.height(),true);
            //         },
            //         start: function(event, ui) {
            //             _this.widgetSelected(divAdd);
            //         },
            //         stop: function(event, ui) {
            //         }
            //     });
            //     divAdd.click(function () {
            //         _this.widgetSelected($(this));
            //     });
            //     this.bindMenu(divAdd,type);
            // }
            divAdd.css('z-index', itemData['zindex']);
            $('#compont').append(divAdd);
        },
        bindMenu(divAdd, type) {
            let _this = this;
            divAdd.contextMenu('myMenu', {
                menuStyle: {
                    border: '0'
                },
                bindings: {
                    'item_1': function(t) {
                        $('#' + t.id).remove();
                        _this.removeWidget(t.id,type);
                    }
                }
            });
        },
        removeWidget(id, type) {
            this.resetVal();
            var deleteId = this.widgetData.get(id)['id'];
            if (deleteId !== undefined && deleteId != null && deleteId !== '') {
                this.discardIds += deleteId + ',';
            }
            this.widgetData.remove(id);
            if (type === 'Imp' || type === 'Text' || type === 'Button' || type === 'Hd') {
                console.log(111)
            } else {
                var a = $('#accordion').find('a[name=' + type + ']');
                a.removeClass('notclick');
                a.addClass('addWiget');
            }
        },
        resetVal() {
            this.attrForm.X = 0
            this.attrForm.Y = 0
            this.attrForm.W = 0
            this.attrForm.H = 0
        },
        initNeedAddWidgetInfo(name, screenData, svl) {
            if( this.widgetData.size() == 4 ) {
                this.$message.error('一个终端只能添加4个屏幕')
                return
            }
            var rotate = screenData.rotate || 0;
            var addWidth = screenData.width;
            var addHeight = screenData.height;
            if(addWidth > Number(this.templateOpts.width)) {
                this.$message.error('屏幕宽度超过终端宽度,不能添加')
                return
            }
            if(addHeight > Number(this.templateOpts.height)) {
                this.$message.error('屏幕高度超过终端高度,不能添加')
                return
            }
            // 清空属性值
            this.resetVal();
            const id = screenData.id
            const $this = $("[name='" + name + id + "']");
            var type = $this.attr('name');
            var index = $this.attr('index');
            var key = type + index;
            var itemData = {};
            itemData['width'] = addWidth // Math.round(addWidth * this.iwidthPercent);
            itemData['height'] = addHeight // Math.round(addHeight * this.iheightPercent);
            itemData['x'] = '0';
            itemData['y'] = '0';
            itemData['name'] = $this.text();
            itemData['type'] = type;
            itemData['index'] = index;
            itemData['id'] = id
            itemData['svl'] = svl
            itemData['rotate'] = rotate
            $this.attr('index', Number(index) + 1);
            this.widgetData.put(key, itemData);
            this.addWiget(itemData, type);
            this.doUpdateAttrForm(key);

            console.log('name:'+name, 'index:'+index, 'key:'+key, 'type:'+type, itemData)
        }
    }
}
